package util

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"mumu_stock_trad/model"
	"net/http"
)

const (
	apiURL = "https://stock.xueqiu.com/v5/stock/realtime/quotec.json?symbol=%s"
)

// FetchStockData 从 API 获取股票数据
func FetchStockData(symbol string) (model.StockData, error) {
	url := fmt.Sprintf(apiURL, symbol)

	fmt.Println(url)

	// 发起 HTTP 请求获取数据
	resp, err := http.Get(url)
	if err != nil {
		return model.StockData{}, fmt.Errorf("failed to fetch data from API: %v", err)
	}
	defer resp.Body.Close()

	// 读取 HTTP 响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return model.StockData{}, fmt.Errorf("failed to read response body: %v", err)
	}

	// 定义结构体以解析 JSON
	var response struct {
		Data []struct {
			Symbol             string  `json:"symbol"`               // 股票代码
			Current            float64 `json:"current"`              // 当前价格
			Percent            float64 `json:"percent"`              // 涨跌幅百分比
			Chg                float64 `json:"chg"`                  // 涨跌额
			Timestamp          int64   `json:"timestamp"`            // 时间戳
			Volume             float64 `json:"volume"`               // 成交量
			Amount             float64 `json:"amount"`               // 成交额
			MarketCapital      float64 `json:"market_capital"`       // 市值
			FloatMarketCapital float64 `json:"float_market_capital"` // 流通市值
			TurnoverRate       float64 `json:"turnover_rate"`        // 换手率
			Amplitude          float64 `json:"amplitude"`            // 振幅
			Open               float64 `json:"open"`                 // 开盘价
			LastClose          float64 `json:"last_close"`           // 昨日收盘价
			High               float64 `json:"high"`                 // 最高价
			Low                float64 `json:"low"`                  // 最低价
			AvgPrice           float64 `json:"avg_price"`            // 平均价格
			CurrentYearPercent float64 `json:"current_year_percent"` // 今年涨跌幅百分比
		} `json:"data"`
	}

	// 解析 JSON 响应
	err = json.Unmarshal(body, &response)
	if err != nil {
		return model.StockData{}, fmt.Errorf("failed to unmarshal JSON response: %v", err)
	}

	// 只取第一个股票数据
	if len(response.Data) == 0 {
		return model.StockData{}, fmt.Errorf("no data returned from API")
	}
	data := response.Data[0]

	// 构造 StockData 结构体并返回
	stockData := model.StockData{
		Symbol:             data.Symbol,
		Current:            data.Current,
		Percent:            data.Percent,
		Chg:                data.Chg,
		Timestamp:          data.Timestamp,
		Volume:             data.Volume,
		Amount:             data.Amount,
		MarketCapital:      data.MarketCapital,
		FloatMarketCapital: data.FloatMarketCapital,
		TurnoverRate:       data.TurnoverRate,
		Amplitude:          data.Amplitude,
		Open:               data.Open,
		LastClose:          data.LastClose,
		High:               data.High,
		Low:                data.Low,
		AvgPrice:           data.AvgPrice,
		CurrentYearPercent: data.CurrentYearPercent,
	}

	return stockData, nil
}
